package controller

import (
	"encoding/base64"
	"strings"

	"device-admin/internal/app/grpc/service/pubsub"
	"device-admin/internal/app/web/service/alarm"
	"device-admin/internal/define"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/response"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

type Alarm struct{}

// GetAlarmType 获取报警类型
func (Alarm) GetAlarmType(c *gin.Context) {
	type alarmType struct {
		ID      int    `json:"id"`
		Name    string `json:"name"`
		Visible bool   `json:"visible"`
	}
	var alarmTypes []alarmType
	for k, alarm := range define.AlarmType {
		alarmTypes = append(alarmTypes, alarmType{
			ID:      k,
			Name:    alarm.Name,
			Visible: alarm.Visible,
		})
	}
	response.JSON(c, alarmTypes, nil)
}

// AlarmNotifySetting
func (Alarm) AlarmNotifySetting(c *gin.Context) {
	var params struct {
		RobotIDs string `json:"robot_ids"`
		WildMsg  string `json:"wildMsg"`
	}
	c.ShouldBindBodyWith(&params, binding.JSON)
	dataBytes, err := base64.StdEncoding.DecodeString(params.WildMsg)
	if err != nil {
		response.JSON(c, nil, errorx.New("无效的wildmsg", -1))
		return
	}

	// 批量操作
	robotArray := strings.Split(params.RobotIDs, ",")
	for _, robotID := range robotArray {
		pubsub.CMDPublish(robotID, "95", "wildmsg", base64.StdEncoding.EncodeToString(dataBytes))
	}
	response.JSON(c, nil, nil)
}

// GetAlarmNotifySetting 获取告警通知配置记录
func (Alarm) GetAlarmNotifySetting(c *gin.Context) {
	list, total, _ := alarm.AlarmSettingRecords(c.Query("robot_id"))
	response.JSON(c, map[string]interface{}{
		"list":  list,
		"total": total,
	}, nil)
}

// GetAlarmReport 告警分析统计
func (Alarm) GetAlarmReport(c *gin.Context) {
}
